$package('wstuo.knowledge');

$import('wstuo.user.userUtil');
$import('itsm.app.autocomplete.autocomplete');
/**
 * 知识库主函数
 */
wstuo.knowledge.directKnowledges=function(){
	this._url ="knowledgeInfo!findAllKnowledges.action";
	
	return {
       
		/**
         * @description 标题格式化
         */
        knowledgeGridTitleFormatter: function (cell, opt, data) {
            return "<a style='color:green' href=javascript:wstuo.knowledge.directKnowledges.showKnowledgeDetail('" + data.kid + "')>" + cell + "</a>";
        },
        
        /**
		 *@description 根据ID显示知识详细信息
		 *@param id 知识编号
		 */
		showKnowledgeDetail:function(id){
			
			var url="knowledgeInfo!showKnowledge.action?kid="+id;
			wstuo.knowledge.directKnowledges.reOpenTab(url,i18n['knowledge']+i18n['details']);
			
		},

		/**
		 * @description 如果当前TAB存在，则关闭TAB再打开新的TAB,与refreshTab一样，只是参数顺序不一样
		 */
		reOpenTab:function(url,title){
			if ($('#itsmMainTab').tabs('exists',title))
			{
				$('#itsmMainTab').tabs('close',title);
				$('#itsmMainTab').tabs('add',{
					title:title,
					cache:"true",
		 			href:url+'&random='+new Date().getTime(),
					closable:true
				});
			} 
			else 
			{
				$('#itsmMainTab').tabs('add',{
					title:title,
					cache:"true",
		 			href:url+'&random='+new Date().getTime(),
					closable:true
				});
			}
			//wstuo.knowledge.directKnowledges.tabClose();
		},
		/**
		 * 关闭选项卡.
		 * @param title 选项卡标题
		 **/
		closeTab:function(title){
			if ($('#itsmMainTab').tabs('exists',title)){
				$('#itsmMainTab').tabs('close',title);
			}
		},
        /**
         * 状态格式化
         */
        statusFormatter:function(cell,event,data){
        	
        	var _status={'1':i18n['knowledge_satus_normal'],'0':i18n['knowledge_satus_approving'],'-1':i18n['title_refused']};
        	
        	return _status[cell];
        },
        /**
         * 显示数据到表格
         */
        showJqgrid:function(){
			var params = $.extend({},jqGridParams, {
                url:_url,
                caption: i18n['title_request_knowledgeGrid'],
                colNames: [i18n['number'],i18n['label_knowledge_relatedService'],i18n['title'],i18n['title_creator'], i18n['knowledge_knowledgeCategory'], i18n['title_createTime'],i18n['common_updateTime'],i18n['status'],''],
                colModel: 
                [
	                { name: 'kid',width: 50, align:'center'}, 
	                { name:'knowledgeServiceName',width:120,align:'center',sortable: false},
	                { name: 'title', align:'center', width: 280,formatter:wstuo.knowledge.directKnowledges.knowledgeGridTitleFormatter },               
	                { name: 'creatorFullName',width: 90,align: 'center'},
	                
	                { name: 'categoryName', width: 80,align: 'center',sortable: false},
	                
	                { name: 'addTime',width: 180,align: 'center',formatter: timeFormatter},
	                { name: 'lastUpdateTime', width: 180,align: 'center', formatter: timeFormatter},
	                { name: 'knowledgeStatus',width: 80,align: 'center',sortable: false,
	                    formatter:wstuo.knowledge.directKnowledges.statusFormatter},
	                { name: 'statusDesc',hidden: true }
	                
                ],
                jsonReader: $.extend(jqGridJsonReader, {
                    id: "kid"
                }),
                sortname: 'kid',
                height:'100%',
                ondblClickRow:function(rowId){wstuo.knowledge.directKnowledges.showKnowledgeDetail(rowId)},
                pager: '#knowledgeGridPager'
            });
            $("#knowledgeGrid").jqGrid(params);
            $("#knowledgeGrid").navGrid('#knowledgeGridPager', navGridParams);
            $("#t_knowledgeGrid").css(jqGridTopStyles);
            $("#t_knowledgeGrid").html($("#knowledgeGridToolbar").html());
            //自适应宽度
            setGridWidth("#knowledgeGrid", "regCenter",20);
        },
        /**
         * @description 搜索
         */
        search_konwledge: function () {
        	var _postData={
        			'knowledgeQueryDto.title':$('#search_knowTitle').val(),
        			'knowledgeQueryDto.content':$('#search_kncontent').val()};
            var postData = $("#knowledgeGrid").jqGrid("getGridParam", "postData");
            $.extend(postData, _postData); //将postData中的查询参数覆盖为空值
        	$('#knowledgeGrid').jqGrid('setGridParam',{url:_url,page:1,postData:_postData}).trigger('reloadGrid');
        },
        /**
         * @description 打开高级搜索框
         */
        search_konwledge_openwindow: function () {
        	$("#knowledgeSearchDiv").css("display","block");
        	//itsm.app.autocomplete.autocomplete.bindAutoComplete('#search_knTitle','com.wstuo.itsm.knowledge.entity.KnowledgeInfo','title','title','kid','Long','','');//标题
            windows('knowledgeSearchDiv',{width: 350,close:function(){
            }});
        },
        /**
         * @description 查找，打开下拉树.
         * 
         */
        showKnowledgeCategory: function(){
        	wstuo.knowledge.directKnowledges.selectKnowledgeCategory('#knowledge_category_select_window','#knowledge_category_select_tree','#search_knCategory','#search_eventId');
        },
        /**
		 * 显示知识库分类.
		 */
		selectKnowledgeCategory:function(windowId,treeId,nameId,valueId){
			windows(windowId.replace('#',''),{width:240});
			wstuo.knowledge.directKnowledges.showKnowledgeTree(treeId,function(e,data){
				wstuo.knowledge.directKnowledges.selectKnowledgeCategory_selectNode(e,data,windowId,treeId,nameId,valueId);
			});
			
		},
		selectKnowledgeCategory_selectNode:function(e,data,windowId,treeId,nameId,valueId){
			var obj = data.rslt.obj;
			var _parent = data.inst._get_parent();
			if($vl(obj.attr('cname'))==="More..." && obj.attr('start')!=undefined){
				$.ajax({
					type:"post",
					url :"event!getCategoryTree.action?flag=dataDic&num="+category_num+"&start="+obj.attr('start')+"&types=Knowledge&parentEventId="+(_parent.attr ? _parent.attr("id").replace("node_",""):0),
	                dataType: 'json',
	                cache:false,
					success:function(data0){
						var bool=false;
						$.each(data0, function(s, n) {
							$(treeId).jstree("create_node", obj, "before", n
							).bind("select_node.jstree",function(e,data1){
								wstuo.knowledge.directKnowledges.selectKnowledgeCategory_selectNode(e,data1,windowId,treeId,nameId,valueId);
							});
							bool=n.attr.bool;
						});
						obj.attr('start',parseInt(obj.attr('start'))+1);
						if(!bool){
							msgShow("没有更多了...",'show');
							obj.attr('cname',"NoMore");
						}
						
				    }
				});
			}else if($vl(obj.attr('cname'))==="NoMore"){
				msgShow("没有更多了...",'show');
			}else{
                $(nameId).val(obj.attr('cname'));
                $(valueId).val(obj.attr('id'));
				$(windowId).dialog('close');
			}
		},
		/**
		 * 显示知识库分类树.
		 * @param treeDIV 树结构所在的div：$(treeDIV)
		 * @param selectNode 选择节点的回调函数
		 */
		showKnowledgeTree:function(treeDIV,selectNode){
			
			 $(treeDIV).jstree({
					json_data: {
						ajax: {
						  type:"post",
						  //url : "event!getCategoryTree.action?num="+category_num+"",
						  url : "event!getCategoryTree.action?flag=view&pageFlag=direct&num="+category_num,
					      data: {'types': 'Knowledge'},
		                  dataType: 'json',
		                  cache:false
					 	}
					},
				"plugins" : [ "themes", "json_data", "ui", "crrm","dnd", "search", "types", "hotkeys"]
			})
			.bind("select_node.jstree", function(e,data){
				selectNode(e,data);
			 });
		},
		/**
		 * 显示知识库分类树,只读
		 * @param treeDIV 树结构所在的div：$(treeDIV)
		 * @param selectNode 选择节点的回调函数
		 */
		showKnowledgeTree_view:function(treeDIV,selectNode){
			
			 $(treeDIV).jstree({
					json_data: {
						ajax: {
						  type:"post",
						  url : "event!getCategoryTree.action?flag=view&pageFlag=direct&num="+category_num,
					      data:function(n){
					    	  return {'types': 'Knowledge','parentEventId':n.attr ? n.attr("id").replace("node_",""):0};//types is in action
					      },
		                  dataType: 'json',
		                  cache:false
					 	}
					},
				"plugins" : ["themes", "json_data", "ui", "crrm", "types", "hotkeys"]
			})
			.bind("select_node.jstree", function(e,data){
				selectNode(e,data);
			 });
		}, 
        /**
         * @description 高級搜索
         */
        doSearchKnowledge: function () {
        	if($('#knowledgeSearchDiv').form('validate')){
        		
	            var sdata = $('#knowledgeSearchDiv form').getForm();
	            
	            var postData = $("#knowledgeGrid").jqGrid("getGridParam", "postData");
	            $.extend(postData, sdata); //将postData中的查询参数覆盖为空值

	            $('#knowledgeGrid').jqGrid('setGridParam', {
	                url: _url,
	                page: 1
	            }).trigger('reloadGrid');
        	}

        },
        /**
         * 显示首页LOGO
         */
        showIndexLogo:function(){
			var url = 'organization!findCompany.action?companyNo=1';
			$.post(url,function(res){
				if($(res.logo)!=''){
					$('#、').attr({'src':'organization!findImage.action?company.orgNo=1'});
					if(res.homePage != ''){
						$('#index_logo_href').attr({'href':res.homePage});
					}else{
						$('#index_logo_href').attr({'onClick':'javascript:basics.tab.tabUtils.addTab("'+i18n.companyInformation+'","../pages/security/company.jsp")'});
					}					
				}
			});		
		},
		showKnowledgeTree_view_selectNode:function(e,data){  
			var obj = data.rslt.obj;
			var _parent = data.inst._get_parent();
			if($vl(obj.attr('cname'))==="More..." && obj.attr('start')!=undefined){
				$.ajax({
					type:"post",
					url :"event!getCategoryTree.action?flag=dataDic&num="+category_num+"&start="+obj.attr('start')+"&types=Knowledge&parentEventId="+(_parent.attr ? _parent.attr("id").replace("node_",""):0),
	                dataType: 'json',
	                cache:false,
					success:function(data0){
						var bool=false;
						$.each(data0, function(s, n) {
							$("#knowledgeCategoryTree").jstree("create_node", obj, "before", n
							).bind("select_node.jstree",function(e,data1){
								wstuo.knowledge.directKnowledges.selectKnowledgeCategory_selectNode(e,data1,windowId,treeId,nameId,valueId);
							});
							bool=n.attr.bool;
						});
						obj.attr('start',parseInt(obj.attr('start'))+1);
						if(!bool){
							msgShow("没有更多了...",'show');
							obj.attr('cname',"NoMore");
						}
				    }
				});
			}else if($vl(obj.attr('cname'))==="NoMore"){
				msgShow("没有更多了...",'show');
			}else{
		   		var _name=obj.attr('cname');
		   		var _kid=obj.attr('id');
	  			if(_name == i18n['knowledge_knowledgeCategorys']){
	  				_name="";	
	  			}
	  			else{
	  				var _postData={
	  						'knowledgeQueryDto.eventId':_kid,
	  						'knowledgeQueryDto.category': _name,
	  						'knowledgeQueryDto.title':'',
	  						'knowledgeQueryDto.endTime':'',
	  						'knowledgeQueryDto.keyWord':'',
	  						'knowledgeQueryDto.startTime':'',
	  						'knowledgeQueryDto.attachmentContent':''
	  				};
	  	            var postData = $("#knowledgeGrid").jqGrid("getGridParam", "postData");
	  	            $.extend(postData, _postData); 
	  				$('#knowledgeGrid').jqGrid('setGridParam',{url:_url,page:1,postData:_postData}).trigger('reloadGrid');
	  			}
			}
          },
		/**
		 * 初始化加载
		 * @private
		 */
		init:function() {
			_url = 'knowledgeInfo!findAllKnowledges.action?knowledgeQueryDto.opt=&knowledgeQueryDto.loginUserName=enduser';
	        //加载树结构
			wstuo.knowledge.directKnowledges.showKnowledgeTree_view('#knowledgeCategoryTree',function(e,data){    		 
				wstuo.knowledge.directKnowledges.showKnowledgeTree_view_selectNode(e,data);
	          });
			wstuo.knowledge.directKnowledges.showJqgrid();
			
			// 设置一个定时器确保标题和内容输入框获取焦点后才绑定回车事件进行搜索
			setInterval(function(){
                if (
                        (document.activeElement.id == 'search_knowTitle') ||
                        (document.activeElement.id == 'search_kncontent')
                   ) {
                    $(document).bind('keypress', function(event){ 
                        if(event.keyCode == '13')
                            wstuo.knowledge.directKnowledges.search_konwledge();
                    });
                } else {
                    $(document).unbind('keypress');
                }
            }, 500);
			$('#search_knCategory').click(wstuo.knowledge.directKnowledges.showKnowledgeCategory);
			$('#search_creator_select').click(function(){
            	 wstuo.user.userUtil.selectUser('#search_creator','','','fullName',companyNo);
            });
			$('#know_search_endTime,#know_search_startTime').datepicker({changeMonth:true,changeYear:true});
			$(window).resize(function(){
				setGridWidth("#knowledgeGrid", "regCenter",20);
			});
		}
	}
}();
$(document).ready(wstuo.knowledge.directKnowledges.init);